<?php

namespace App\Http\Requests\Backend;

use App\Models\School;
use App\Models\UserRole;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

/**
 * Class EditUser
 * @package App\Http\Requests\Backend
 */
class EditUser extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|string',
            'phone' => [
                'required',
                'regex:/^1[3|4|5|7|8|9][0-9]{9}$/',
                Rule::unique('users')->ignore((int)trim(strrchr(Request()->path(), '/'),'/'))
            ],
            'school_id' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (School::query()->where('status', School::STATUS_ACTIVE)->find($value)->doesntExist()) {
                        return $fail('未找到学校');
                    }
                }
            ],
            'role_id' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (UserRole::query()->where('school_id', $this->school_id)->find($value)->doesntExist()) {
                        return $fail('未找到该角色');
                    }
                }
            ],
            'sex' => 'integer|nullable',
            'user_no' => 'string|nullable'
        ];
    }

    /**
     * @return array
     */
    public function attributes()
    {
        return [
            'name' => '姓名',
            'phone' => '手机号码',
            'school_id' => '学校',
            'role_id' => '用户角色',
            'sex' => '性别',
            'user_no' => '教工号'
        ];
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'name.string' => ':attribute数据类型错误',
            'user_no.string' => ':attribute数据类型错误',
            'sex.integer' => ':attribute数据类型错误',
            'role_id.required' => '请选择:attribute',
            'school_id.required' => '请选择:attribute',
            'name.required' => '请填写:attribute',
            'phone.required' => '请填写:attribute',
            'phone.regex' => ':attribute格式错误',
            'phone.unique' => '已存在相同的:attribute'
        ];
    }
}
